package cn.j0n4than.accountingtool.controller.api.user;

import cn.j0n4than.accountingtool.config.ResponseConfig;
import cn.j0n4than.accountingtool.entity.Spending;
import cn.j0n4than.accountingtool.entity.User;
import cn.j0n4than.accountingtool.pojo.request.UserProfileRequest;
import cn.j0n4than.accountingtool.utils.BcryptUtil;
import cn.j0n4than.accountingtool.utils.Response;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 用户中心控制器
 *
 * @author jonathan
 */
@RestController
@RequestMapping("/api/user")
public class UserHomeController extends UserBaseController {

    /**
     * 返回用户仪表盘需要的数据
     *
     * @return Response
     */
    @GetMapping("/dashboard")
    public Response dashboard() {
        User currentUser = this.getCurrentUser();

        Spending spending = new Spending();
        spending.userId = currentUser.id;

        Response response = Response.success();

        //日支出
        BigDecimal spendingAmountToday = this.spendingService.getSpendingAmountToday(currentUser.id);
        //周支出
        BigDecimal spendingAmountThisWeek = this.spendingService.getSpendingAmountThisWeek(currentUser.id);
        //月支出
        BigDecimal spendingAmountThisMonth = this.spendingService.getSpendingAmountThisMonth(currentUser.id);
        //总支出
        BigDecimal spendingAmount = this.spendingService.getSpendingAmount(spending);
        //近期消费数据
        List<Spending> topData = this.spendingService.getTopData(currentUser.id, 10);

        response.setResult("spendingAmountToday", spendingAmountToday)
                .setResult("spendingAmountThisWeek", spendingAmountThisWeek)
                .setResult("spendingAmountThisMonth", spendingAmountThisMonth)
                .setResult("spendingAmount", spendingAmount)
                .setResult("topData", topData);
        return response;
    }

    /**
     * 获取当前请求的用户信息
     *
     * @return Response
     */
    @GetMapping("/getCurrentUserInfo")
    public Response getCurrentUserInfo() {
        User currentUser = this.getCurrentUser();
        currentUser.password = null;
        return Response.success().setResult("user", currentUser);
    }

    /**
     * 修改密码功能
     *
     * @param request       请求体
     * @param bindingResult 验证结果
     * @return Response
     * @see UserProfileRequest
     */
    @PostMapping("/updatePassword")
    public Response updatePassword(@Validated @RequestBody UserProfileRequest request, BindingResult bindingResult) {
        Response response = Response.response();
        this.checkValidate(response, bindingResult);
        if (response.getStatus() == ResponseConfig.ERROR) {
            return response;
        }

        if (!request.getNewPassword().equals(request.getConPassword())) {
            return response
                    .setStatus(ResponseConfig.ERROR)
                    .setMessage("两次输入的密码不一致");
        }
        if (!BcryptUtil.passwordVerify(request.getOldPassword(), this.getCurrentUser().password)) {
            return response
                    .setStatus(ResponseConfig.ERROR)
                    .setMessage("旧密码输入错误");
        }
        User currentUser = this.getCurrentUser();
        currentUser.password = BcryptUtil.passwordHash(request.getNewPassword());
        if (this.userService.update(currentUser.id, currentUser) > 0) {
            //使这个token失效
            this.removeToken();
            return response.setStatus(ResponseConfig.SUCCESS).setMessage("修改密码成功");
        }
        return response.setStatus(ResponseConfig.ERROR).setMessage("未知错误");
    }

    /**
     * 注销登陆
     *
     * @return Response
     */
    @RequestMapping("/logout")
    public Response logout() {
        Response response = Response.response();
        if (this.removeToken()) {
            response.setStatus(ResponseConfig.SUCCESS);
            response.setMessage("注销登陆成功");
        } else {
            response.setStatus(ResponseConfig.ERROR);
            response.setMessage("注销登陆失败");
        }

        return response;
    }

    /**
     * 移除redis中的token
     *
     * @return boolean
     */
    private boolean removeToken() {
        return redisUtil.delete(Integer.toString(this.getCurrentUser().id));
    }
}
